<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;
use OSS\OssClient;
use OSS\Core\OssException;
error_reporting(E_ALL ^ E_NOTICE);
//获取时间戳的绝对周数（1970年01月01日为第0周）
function get_absolute_week($timestamp = null){
    if ($timestamp==null){
        $timestamp=time();
    }
    $beginWeek = mktime(0,0,0,date("m",$timestamp),date("d",$timestamp)-date("w",$timestamp)+1,date("Y",$timestamp));
    $res = ( $beginWeek - ((4*24*60*60)-(8*60*60)) )/(7*24*60*60);
    return $res;
}
//经纬度转换成三角函数中度分表形式。
function Rad($d){
    return $d * pi() / 180.0;
}
//获取2个地理坐标的距离
function get_distance($lng1,$lat1,$lng2,$lat2){
    $radLat1 = Rad($lat1);
    $radLat2 = Rad($lat2);
    $a = $radLat1 - $radLat2;
    $b = Rad($lng1) - Rad($lng2);
    $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)));
    $s = $s *6378.137 ;// EARTH_RADIUS;
    $s = round($s * 10000) / 10000; //输出为公里
    $s=round($s,4);
    return $s;
}

// 应用公共文件
function get_table_comment($table)
{
    $table = Db::name($table)->getTable();
    $re = Db::query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $table . "'");
    $comments = [];
    if (is_array($re)) {
        foreach ($re as $key => $item) {
            if ($item['COLUMN_COMMENT']) {
                $comments[$item['COLUMN_NAME']] = $item;
            } else {
                $item['COLUMN_COMMENT'] = $item['COLUMN_NAME'];
                $comments[$item['COLUMN_NAME']] = $item;
            }

        }
    } else {
        return false;
    }

    return $comments;
}

function get_curl($model, $action, $params = [])
{
    $model_api = Config("model_api.{$model}");
    //$model_api = Config('model_api.'.$model);
    $url = $model_api . "/" . $action;
    $result = \tools\curl\Curl::get($url, $params);
    if (!$result) {
        $result['status'] = false;
        $result['msg'] = '请求失败';
        $result['url'] = $url;
        $result['params'] = $params;
    } else {
        $result = \tools\curl\Curl::json2arr($result);
        if ($result['status'] === false)
            $result['data'] = '数据不存在';
    }
    return $result;
}
function post_curl($model, $action, $params = [])
{
    $model_api = Config("model_api.{$model}");
    //$model_api = Config('model_api.'.$model);
    $url = $model_api . "/" . $action;
    $result = \tools\curl\Curl::post($url, $params);
    if (!$result) {
        $result['status'] = false;
        $result['msg'] = '请求失败';
    } else {
        $result = \tools\curl\Curl::json2arr($result);
        if ($result['status'] === false)
            $result['data'] = '数据不存在';
    }
    return $result;
}

function get_token($length){
    //随机生成指定长度字符串
    $token_str = substr(str_shuffle('abcedfghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
    return $token_str;
}
/**
 * 生成,保存并返回token
 * @param $user_id  用户id
 */
function save_token($account_id)
{
    //随机生成20位字符串
    $token_str = substr(str_shuffle('abcedfghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 20);

    //token表需要的字段
    $token['account_id'] = $account_id;
    $token['token'] = $token_str;
    $token['expires_in'] = 3600;             //有效期60分钟
    $token['create_time'] = time();
    $token['end_time'] = $token['create_time'] + $token['expires_in'];
    $token['sys_ip'] = isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'0.0.0.0';

    //写入token表
//    $res = get_curl('login', '/token/add', $token);
    \think\Db::name('token')->insert($token);
    return $token_str;
}
//字段tinyint 1转true 0转false
function tobool(&$list, $columns)
{
    foreach ($list as $key => $item) {
        foreach ($columns as $column) {
            if ($list[$key][$column]) {
                $list[$key][$column] = true;
            } else {
                $list[$key][$column] = false;
            }
        }
    }
}



/**
 * 获取当前页面完整URL地址
 */
function get_url() {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}

function get_host(){
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') ;
}

/**
 * 记录log
 */
function logs($name, $data) {
    file_put_contents(\think\facade\Env::get('root_path') . 'log/' . $name . "_log.txt", var_export($data, TRUE), FILE_APPEND);
    file_put_contents(\think\facade\Env::get('root_path') . 'log/' . $name . "2_log.txt", print_r($data, TRUE), FILE_APPEND);
    file_put_contents(\think\facade\Env::get('root_path') . 'log/' . $name . "_log.txt", "\r\n", FILE_APPEND);
    file_put_contents(\think\facade\Env::get('root_path') . 'log/' . $name . "2_log.txt", "\r\n", FILE_APPEND);
}
/**
 * POST请求https接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $post [请求的参数]
 * @return  string
 */
function post_curls($url, $post)
{
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $res = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno' . curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $res; // 返回数据，json格式
}

/**
 * POST请求https接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $post [请求的参数]
 * @return  string
 */
function pdo_sql($url, $post)
{
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $res = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno' . curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    return $res; // 返回数据，json格式

}

/**
 * xml转换成json
 */
function xml_to_json($source) {
    if(is_file($source)){
        $xml_array=simplexml_load_file($source);
    }else{
        $xml_array=simplexml_load_string($source);
    }
    $json = json_encode($xml_array);
    return $json;
}

function arr_remove_empty($temp_map){
    //去除为空的条件
    $paginate_map = [];
    foreach ($temp_map as $k=>$v){
        if ($v[2]===null || $v[2]=='' || $v[2]=='%%'){
            continue;
        }
        array_push($paginate_map,$v);
    }
    return $paginate_map;
}

